<template>
  <div>
    <el-main>
      <div class="box">
        <div class="top">
          <div style="margin-right: 60px; display: flex; align-items: center">
            <!-- 搜索按钮 -->
            <el-input
              v-model="queryName"
              style="margin-right: 20px; width: 600px; float: left"
              placeholder="请输入中文名或者拉丁名"
              class="input-with-select"
            >
            </el-input>
            <el-select
              v-model="categoryValue"
              style="margin-right: 20px"
              @change="handleOptionChange"
            >
              <el-option
                v-for="item in categoryOptions"
                :key="item.key"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-button slot="append" @click="onSearch">查询</el-button>
            <el-button type="primary" size="medium" @click="handleAddPlant"
              >添加</el-button
            >
            <!-- Excel批量导入按钮 -->
            <el-button
              type="success"
              style="margin-left: 10px"
              @click="handleExcelImport"
            >
              <i class="el-icon-upload2" />
              Excel批量导入
            </el-button>
          </div>
        </div>

        <div class="center">
          <el-table
            :data="paginatedData"
            border
            style="width: 100%"
            size="medium"
            :max-height="tableheight"
          >
            <el-table-column type="selection" width="55" />
            <!-- <el-table-column prop="id" label="序号" width="60px" /> -->
            <el-table-column width="60px" prop="id" label="序号">
            </el-table-column>
            <el-table-column prop="wzm" label="中文名" show-overflow-tooltip />

            <el-table-column prop="ldm" label="学名" show-overflow-tooltip />

            <el-table-column
              prop="mengshi"
              label="盟市"
              show-overflow-tooltip
            />
            <el-table-column
              prop="qixian"
              label="旗县（区）"
              show-overflow-tooltip
            />
            <el-table-column prop="jd" label="经度" show-overflow-tooltip />
            <el-table-column prop="wd" label="纬度" show-overflow-tooltip />
            <el-table-column prop="hb" label="海拔" show-overflow-tooltip />
            <el-table-column
              prop="diaochariqi"
              label="调查时间"
              width="150"
              show-overflow-tooltip
            />

            <el-table-column
              prop="action"
              label="操作"
              width="170"
              align="center"
            >
              <template slot-scope="scope">
                <!-- 操作按钮 -->
                <el-button
                  type="primary"
                  size="mini"
                  @click="xiugai(scope.row)"
                >
                  修改
                </el-button>
                <el-button
                  type="danger"
                  size="mini"
                  @click="deleteItem(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="bottom">
          <el-pagination
            :current-page="currentPage"
            background
            layout="total, prev, pager, next, jumper"
            :total="totalItems"
            :page-size="pageSize"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- Excel导入数据展示弹框 -->
      <el-dialog
        title="Excel数据预览"
        :visible.sync="excelImportDialogVisible"
        width="90%"
        :close-on-click-modal="false"
        @close="handleExcelDialogClose"
      >
        <div class="excel-preview-container">
          <el-table
            :data="paginatedExcelData"
            border
            stripe
            style="width: 100%"
            max-height="500"
            :header-cell-style="{
              fontWeight: 'bold',
              backgroundColor: '#f5f7fa',
            }"
          >
            <el-table-column
              v-for="header in excelHeaders || []"
              :key="header.key"
              :prop="header.prop"
              :label="header.label"
              
              show-overflow-tooltip
            />
          </el-table>

          <div class="excel-pagination">
            <el-pagination
              :current-page="excelCurrentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="excelPageSize"
              :total="excelData ? excelData.length : 0"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleExcelSizeChange"
              @current-change="handleExcelCurrentChange"
            />
          </div>
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button @click="handleExcelDialogClose">关闭</el-button>
          <el-button type="primary" @click="handleConfirmImport"
            >确认导入</el-button
          >
        </div>
      </el-dialog>
    </el-main>
    <!-- 页面内容 -->
  </div>
</template>

<script>
import commonOper from "../../../utils/commonOper";
import { readAnimalSurveyPoints } from "../../../utils/readPlantExcel.js";
import config from "@/config/config.js";
import { getToken } from "@/utils/auth";
export default {
  // 组件逻辑
  data() {
    return {
      tableheight: 300,
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的数据量
      totalItems: 0, // 总项目数
      dialogVisible: false,
      isButtonDisabled: false, // 初始化按钮可点击状态

      buttonText: "录入全部数据",
      formDataExcel: [],
      errorMessages: [],

      queryName: "",
      tableData: [],
      paginatedData: [], // 当前页的数据
      filteredData: [],
      delIds: [],
      // Excel导入相关
      excelImportDialogVisible: false,
      excelData: [],
      excelHeaders: [
        { key: 1, prop: "xh", label: "序号" },
        { key: 2, prop: "wzm", label: "中文名" },
        { key: 3, prop: "ldm", label: "学名" },
        {
          key: 4,
          prop: "shitishuliang",
          label: "实体数量",
        },
        {
          key: 5,
          prop: "henjishuliang",
          label: "痕迹种类及数量",
        },
        { key: 6, prop: "jd", label: "经度" },
        { key: 7, prop: "wd", label: "纬度" },
        { key: 8, prop: "hb", label: "海拔" },
        { key: 9, prop: "podu", label: "坡度" },
        { key: 10, prop: "powei", label: "坡位" },
        { key: 11, prop: "poxiang", label: "坡向" },
        { key: 12, prop: "qixi", label: "栖息地类型" },
        { key: 13, prop: "diaochariqi", label: "调查日期" },
        { key: 14, prop: "discoveryTime", label: "发现时间" },
        { key: 15, prop: "qixiganrao", label: "栖息地干扰" },
        { key: 16, prop: "protectlevel", label: "保护等级" },
        { key: 17, prop: "location", label: "发现地址" },
        { key: 18, prop: "mengshi", label: "盟市" },
        { key: 19, prop: "qixian", label: "旗县（区）" },
        { key: 20, prop: "source", label: "数据来源" },
        { key: 21, prop: "guance", label: "观测者" },
        { key: 22, prop: "zpbh", label: "植物照片编号" },
        { key: 23, prop: "sjzpbh", label: "生境照片编号" },
        {
          key: 24,
          prop: "tezhengmiaoshu",
          label: "物种特征描述",
        },
        {
          key: 25,
          prop: "fenbuduodumiaoshu",
          label: "分布多度描述",
        },
      ],
      excelCurrentPage: 1,
      excelPageSize: 10,
      categoryOptions: [
        { key: 1, label: "全部", value: "" },
        { key: 2, label: "哺乳动物", value: "01" },
        { key: 3, label: "鸟类", value: "02" },
        { key: 4, label: "鱼类", value: "03" },
        { key: 5, label: "节肢动物", value: "04" },
      ],
      categoryValue: "",
    };
  },
  computed: {
    // Excel数据分页计算属性
    paginatedExcelData() {
      if (!this.excelData || !Array.isArray(this.excelData)) {
        return [];
      }
      const start = (this.excelCurrentPage - 1) * this.excelPageSize;
      const end = start + this.excelPageSize;
      return this.excelData.slice(start, end);
    },
  },
  created() {
    const height = document.documentElement.clientHeight - 190;
    this.tableheight = height;
    this.fetchData({
      pageNum: this.currentPage,
      pageSize: this.pageSize,
    });
    // this.getData();
  },
  methods: {
    handleOptionChange(val) {
      this.categoryValue = val;
    },
    fetchData(searchParams) {
      let that = this;
      let params = {
        this: that,
        url:
          config.webapiUrl + "nd/animalsurvey/getAnimalSurveyPointsByCondition",
        data: {
          params: searchParams,
          headers: {
            Authorization: "Bearer " + getToken(),
          },
        },
        successFunc: function (response) {
          that.loading = false;
          let data = response.data.data;
          data.list.forEach(function (element) {
            const date = new Date(element.diaochariqi);

            // 提取日期部分
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从 0 开始，需 +1
            const day = String(date.getDate()).padStart(2, "0");
            const hours = String(date.getHours()).padStart(2, "0");
            const minutes = String(date.getMinutes()).padStart(2, "0");
            const seconds = String(date.getSeconds()).padStart(2, "0");
            // 格式化
            const formattedDate = `${year}-${month}-${day}`;
            element.diaochariqi = formattedDate;
          });

          that.paginatedData = data.list;
          that.totalItems = data.total;
        },
        failFunc: function (response) {
          that.loading = false;
          let params = {
            this: that,
            title: "提示",
            message: "网络异常，请稍后重试！" + response,
            successFunc: function () {},
          };
          commonOper.showWarnAlert(params);
        },
      };
      commonOper.HttpGet(params);
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData({
        pageNum: this.currentPage,
        pageSize: this.pageSize,
      });
    },
    onSearch() {
      let params = {
        name: this.queryName,
        category: this.categoryValue,
        pageNum: this.currentPage,
        pageSize: this.pageSize,
      };
      this.fetchData(params);
    },
    // 新增
    handleAddPlant() {
      this.$router.push({ name: "mammal-add" });
    },
    // 修改
    xiugai(data) {
      // return
      this.$router.push({
        name: "mammal-add",
        query: { data: JSON.stringify(data) },
      });
    },

    deleteItem(id) {
      let that = this;
      this.$confirm("确定要删除这条数据吗？", "删除确认", {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "el-button--danger",
        cancelButtonClass: "el-button--default",
        center: true,
        customClass: "custom-confirm-dialog",
      })
        .then(() => {
          let params = {
            this: that,
            url:
              config.webapiUrl + "nd/animalsurvey/deleteSurveyPoint?id=" + id,
            data: {
              headers: {
                Authorization: "Bearer " + getToken(),
              },
            },
            successFunc: function (response) {
              that.loading = false;
              // 使用更美观的成功提示
              that.$message({
                type: "success",
                message: "数据删除成功！",
                duration: 3000,
                showClose: true,
                customClass: "custom-message-success",
              });
              that.fetchData({
                pageNum: this.currentPage,
                pageSize: this.pageSize,
              });
            },
            failFunc: function (response) {
              that.loading = false;
              let params = {
                this: that,
                title: "提示",
                message: "网络异常，请稍后重试！" + response,
                successFunc: function () {},
              };
              commonOper.showWarnAlert(params);
            },
          };
          commonOper.HttpGet(params);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
            duration: 2000,
            showClose: true,
          });
        });
    },
    handleDialogClose(done) {
      // 清空相关数据

      // // 调用 done() 完成关闭
      done();
    },
    // Excel导入相关方法
    handleExcelImport() {
      // 创建文件输入元素
      const input = document.createElement("input");
      input.type = "file";
      input.accept = ".xlsx,.xls";
      input.onchange = (event) => {
        const file = event.target.files[0];
        readAnimalSurveyPoints(file)
          .then((data) => {
            // Promise 解析成功，获取数据
            const mergedArray = Object.values(data).flat();
            this.excelData = mergedArray;
            this.excelCurrentPage = 1;
            this.excelImportDialogVisible = true;
            this.$message.success(`成功读取Excel文件，共${mergedArray.length}条数据`);
          })
          .catch((error) => {
            console.error("读取 Excel 文件出错:", error);
          });
      };
      input.click();
    },
    // Excel分页大小改变
    handleExcelSizeChange(val) {
      this.excelPageSize = val;
    },

    // Excel当前页改变
    handleExcelCurrentChange(val) {
      this.excelCurrentPage = val;
    },

    // 关闭Excel导入对话框
    handleExcelDialogClose() {
      this.excelImportDialogVisible = false;
      this.excelData = [];
      this.excelCurrentPage = 1;
    },

    // 确认导入Excel数据
    handleConfirmImport() {
      if (!this.excelData || this.excelData.length === 0) {
        this.$message.warning("没有数据可导入");
        return;
      }
      let jsonData = {
        surveySampleList: this.excelData,
      };
      let that = this;
      let paramscommo = {
        this: that,
        url: config.webapiUrl + "/nd/animalsurvey/batAddSurveyPoint",
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        data: jsonData,
        successFunc: function (response) {
          if (response.data.code == 0) {
            this.excelImportDialogVisible = false;
            that.$message.success("保存成功！");
          } else {
            let params = {
              this: that,
              title: "提示",
              message: "保存失败，请稍后重试！" + response.data.msg,
              successFunc: function () {},
            };
            commonOper.showWarnAlert(params);
          }
        },
        failFunc: function (response) {
          let params = {
            this: that,
            title: "提示",
            message: "网络异常，请稍后重试！" + response.data.data,
            successFunc: function () {},
          };
          commonOper.showWarnAlert(params);
        },
      };
      commonOper.HttpPost(paramscommo);
    },
  },
};
</script>

<style scoped>
.el-main {
  color: #333;
  box-sizing: border-box;
}
/* .box {
  padding: 15px;
  background: rgb(255, 255, 255);
  height: 700px;
  position: relative;
  overflow-y: auto;
} */
.top {
  background-color: rgb(232, 232, 232);
  border-radius: 2px;
  padding-left: 20px;
  padding-top: 8px;
  padding-bottom: 7px;
  overflow: hidden;
}
.center {
  /* height: 400px; */
}
.el-form-item {
  margin-bottom: 2px;
  vertical-align: top;
  margin-right: 16px;
}
.bottom {
  text-align: center;
}

.file-upload {
  margin-right: 20px; /* 调整按钮之间的间距 */
}
.file-upload input {
  display: none;
}

/* 添加样式来美化文件选择按钮 */
.file-upload {
  display: inline-block;
  cursor: pointer;
  padding: 10px 20px;
  background-color: #3498db;
  color: #fff;
  border-radius: 5px;
}

.dialog-content {
  display: flex;
  /* flex-direction: column; */
  /* align-items: center; */
  justify-content: center;
  height: 100%;
}
</style>
